# -*- coding: utf-8 -*-
import json

from common.channel.admin_db import get_channel
from common.order import db as order_db
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)


def check_channel_order(pay_id, money, appid):
    _LOGGER.info('check_channel_order : %s, %s, %s', pay_id, money, appid)
    pay = order_db.get_pay(pay_id)
    if not pay:
        raise ParamError('check_channel_order pay_id: %s invalid' % pay_id)
    if money > pay.total_fee + 2:
        raise ParamError(
            'check_channel_order money: %s invalid, total_fee: %s' % (money, pay.total_fee))

    channel = get_channel(pay.channel_id)
    if not channel:
        raise ParamError('check_channel_order channel: %s invalid' % pay.channel_id)
    channel_info = json.loads(channel.info)
    if appid != channel_info['app_id']:
        raise ParamError('check_channel_order appid: %s invalid, channel_appid' % (appid, channel_info['app_id']))
    # if money < channel_info.get('min_amount', 1) - 1 or money > channel_info.get('max_amount', 60000):
    if money > channel_info.get('max_amount', 60000) + 2:
        raise ParamError('check_channel_order money: %s invalid' % money)
